<?php

class NetflixTitle{
	public $id;
	public $xml;
	public $netflixId;
	
	function __construct($xml){
		if(empty($xml)){
			throw new exception("Empty xml passed to NetflixTitle constructor");
			return;
		}

		$this->xml = $xml;
		
		$this->netflixId = $this->getNetflixId($this->xml);

		$this->id = $this->saveToDb($this->netflixId, $this->xml);
	}
	

	function saveToDb($netflixId, $xml){

		$id = $this->getFromDb($netflixId);
		
		if($id === null){
			$cleanXML = mysql_real_escape_string($xml);	
				
			$insertQuery = "INSERT INTO title (`netflix_id`, `xml`) 
							VALUES ('{$netflixId}', '$cleanXML')";
			
			$insertResult = mysql_query($insertQuery) or die ("Inserting a title failed. Query is: $insertQuery. Error is " . mysql_error());
			
			$id = mysql_insert_id();
			fb($id, "id of new title for netflix id $netflixId");
		}

		return $id;
	}
	
	function getFromDb($netflixId){
		$selectQuery = "SELECT `id` from title WHERE netflix_id = '$netflixId'";

		$selectResult = mysql_query($selectQuery) or die("Query failed $selectQuery with error " . mysql_error());
		
		if(mysql_num_rows($selectResult) == 1){
			$titleInfo = mysql_fetch_assoc($selectResult);
			$id = $titleInfo['id'];
			return $id;
		}
		else{
			return null;
		}
	}

	public function getTitle($xml){
		$xmlObject = new SimpleXMLElement($xml);
		$title = $xmlObject->xpath('./title');
		$title = reset($title);
		return $title['regular'];
	}
	
	public function getNetflixId($xml){
		$xmlObject = new SimpleXMLElement($xml);
		$netflixId = $xmlObject->xpath('./*[@rel = \'http://schemas.netflix.com/catalog/title\']');
		$netflixId = (string)$netflixId[0]['href'];
		return $netflixId;
	}
	
	public function getBoxArt($xml){
		$xmlObject = new SimpleXMLElement($xml);
		$boxArt = $xmlObject->xpath('box_art');
		$boxArt = reset($boxArt);
		return $boxArt['small'];
	}
	
	public function getAvailability($xml){
		$xmlObject = new SimpleXMLElement($xml);
		$queueAvailability = $xmlObject->xpath('category');
		$queueAvailability = $queueAvailability[0][0]; //TODO: Create enumerations of availability types
		return $queueAvailability;
	}
	
	public function getFormat($xml){
		$xmlObject = new SimpleXMLElement($xml);
		$format= $xmlObject->xpath('./category[@scheme = \'http://api.netflix.com/categories/title_formats\']');
		$format = $format[0]['label'][0]; //TODO: Create enumerations of format types
		return $format;
	}
	
	public function getPublicURL($xml){
		$xmlObject = new SimpleXMLElement($xml);
		$publicURL = $xmlObject->xpath("./link[@rel = \"alternate\"]");
		$publicURL = $publicURL[0]['href'];
		return $publicURL;
	}
	
	function toString() {
		return "<a href=\"{$this->getPublicURL($this->xml)}\"><img src=\"{$this->getBoxArt($this->xml)}\" /><br />" .
			"Title: {$this->getTitle($this->xml)} " .
			"Availability: {$this->getAvailability($this->xml)} " .
			"Format: {$this->getFormat($this->xml)}" .
			"</a><br />";
	}
	
}

?>